package com.lyhengtongwl.zqsnews.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.gifdecoder.GifDecoder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.adapter.QDNewsAdapter;
import com.lyhengtongwl.zqsnews.entity.BaseEntity;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.entity.NewsEntity;
import com.lyhengtongwl.zqsnews.entity.NewsMainNoticeEntity;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.ui.activity.AuthenticationActivity;
import com.lyhengtongwl.zqsnews.ui.activity.ConectUsActivity;
import com.lyhengtongwl.zqsnews.ui.activity.ConfirmOrderActivity;
import com.lyhengtongwl.zqsnews.ui.activity.GoodsDetailActivity;
import com.lyhengtongwl.zqsnews.ui.activity.NewsWebDetailActivity;
import com.lyhengtongwl.zqsnews.ui.activity.RechargeActivity;
import com.lyhengtongwl.zqsnews.ui.activity.WelActivity;
import com.lyhengtongwl.zqsnews.utils.AppConfig;
import com.lyhengtongwl.zqsnews.utils.CheckApkExist;
import com.lyhengtongwl.zqsnews.utils.CopyUtils;
import com.lyhengtongwl.zqsnews.utils.DataCleanManager;
import com.lyhengtongwl.zqsnews.utils.Downloadutils;
import com.lyhengtongwl.zqsnews.utils.NewsForwardAnimation;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ToastUtil;
import com.lyhengtongwl.zqsnews.utils.UserUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import retrofit2.Response;

import static com.lyhengtongwl.zqsnews.App.activities;

/**
 * Created by Steven on 2019/1/7.
 * 中间dialog的弹出
 */
public class CenterDialog {
    private Activity activity;
    private AlertDialog.Builder builder;
    private View v;
    private FragmentManager fragmentManager;
    private List<NewsEntity> qdList = new ArrayList<>();
    private QDNewsAdapter newsAdapter;
    private static Dialog dialog = null;

    public CenterDialog(int layoutId, Activity activity) {
        this.activity = activity;
        this.builder = new AlertDialog.Builder(activity);
        this.v = (LayoutInflater.from(activity)).inflate(layoutId, null);
    }

    public CenterDialog(int layoutId, Activity activity, FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
        this.activity = activity;
        this.builder = new AlertDialog.Builder(activity);
        this.v = (LayoutInflater.from(activity)).inflate(layoutId, null);
    }

    /**
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */
    public void showPrompt(String title) {
        TextView content = v.findViewById(R.id.prompt_content);
        content.setText(title);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Task.getApiService().loginOut().enqueue(new MyCallback<NewsBaseEntity>(activity) {
                    @Override
                    protected void onSuccess(Response<NewsBaseEntity> response) {
                        UserUtils.clearUserInfo();
                        activity.startActivity(new Intent(activity, WelActivity.class));
                        for (int i = 0; i < activities.size(); i++)
                            activities.get(i).finish();
                        activities.clear();
                        activity.finish();

                    }

                    @Override
                    protected void onFailure(Throwable t) {

                    }
                });
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */
    @SuppressLint("SetTextI18n")
    public void showForBidPrompt(String title, String wxService) {
        TextView content = v.findViewById(R.id.prompt_title);
        content.setText(title);
        TextView content_1 = v.findViewById(R.id.prompt_content);
        content_1.setText("客服微信：" + wxService);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                CopyUtils.copyText(activity, wxService);
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * TODO实名认证
     *
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */

    public void showPromptRZ(String title) {
        TextView content = v.findViewById(R.id.prompt_content);
        content.setText(title);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                activity.startActivity(new Intent(activity, AuthenticationActivity.class));
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 检测版本号 是否是最新的
     */
    public void checkVersion(String title, String downLoadUrl) {
        TextView content = v.findViewById(R.id.prompt_content);
        content.setText(title);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse(downLoadUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                activity.startActivity(intent);
            }
        });

    }

    /**
     * 清除缓存
     */
    public void showPrompt(final TextView tv_cache) {
        TextView content = v.findViewById(R.id.prompt_content);
        content.setText("确认清楚缓存？");
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("SetTextI18n")
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Map<String, ?> map = SPUtils.getAll(activity);
                DataCleanManager.clearAllCache(App.getContext());//清除缓存
                /*删除完之后 进行保存sharePreferences */
                for (int i = 0; i < map.size(); i++) {
                    Set<? extends Map.Entry<String, ?>> set = map.entrySet();
                    for (Map.Entry<String, ?> entry : set) {
                        SPUtils.put(activity, entry.getKey(), entry.getValue());
                    }
                }
                tv_cache.setText("缓存：" + "0M");
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    private static int dip2px(Context mContext, float dpValue) {
        final float scale = mContext.getResources()
                .getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */
    public void showPrompt(String title, String content) {
        TextView prompt_content = v.findViewById(R.id.prompt_content);
        TextView prompt_title = v.findViewById(R.id.prompt_title);
        prompt_title.setText(title);
        prompt_content.setText(content);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                activity.startActivity(new Intent(activity, RechargeActivity.class));
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */
    public void showPrompt_success(String title, String content, final String goodsId, final String saleType) {
        TextView prompt_content = v.findViewById(R.id.prompt_content);
        TextView prompt_title = v.findViewById(R.id.prompt_title);
        prompt_title.setText(title);
        prompt_content.setText(content);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                activity.startActivity(new Intent(activity, ConfirmOrderActivity.class).putExtra("my_type", "order")
                        .putExtra("Id", goodsId)
                        .putExtra("salesType", saleType));
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */
    public void showPrompt_fail(String title, String content, final String issuedNo) {
        TextView prompt_content = v.findViewById(R.id.prompt_content);
        TextView prompt_title = v.findViewById(R.id.prompt_title);
        prompt_title.setText(title);
        prompt_content.setText(content);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //需要判断  是否有下一期  没有下一期  就返回首页
                goNextBidding(issuedNo, dialog);
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
                activity.finish();
            }
        });
    }

    //前往下一期
    private void goNextBidding(String issuedNo, final Dialog dialog) {
        Task.getApiService().nextBid(issuedNo).enqueue(new MyCallback<BaseEntity>(activity) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                if ("0".equals(response.body().getCode())) {
                    //需要重新跳转  到详情页
                    dialog.dismiss();
                    String nextIssuedNo = response.body().getResult().getString("nextIssuedNo");
                    activity.finish();
                    activity.startActivity(new Intent(activity, GoodsDetailActivity.class).putExtra("issuedNo", nextIssuedNo));
                } else {
                    ToastUtil.showShort(activity, response.body().getMessage());
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * @param content 更新描述
     * @param type    //更新类型：0.强制更新； 1.推荐更新； -1.H5模式；
     * @param linkUrl //下载 链接
     */
    public void showUpdatePrompt(final Context ctx, String content, String type, final String linkUrl) {
        ImageView close = v.findViewById(R.id.close_dialog);
        TextView tvDesc = v.findViewById(R.id.tv_desc);
        Button update = v.findViewById(R.id.update_now);

        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 270), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        if ("0".equals(type)) {
            close.setVisibility(View.GONE);
        }
        tvDesc.setText(content);
        tvDesc.setMovementMethod(ScrollingMovementMethod.getInstance());
        close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        update.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!TextUtils.isEmpty(linkUrl)) {
                    Downloadutils.getInstance().crateFileDownloader(ctx, linkUrl);
                }
                dialog.dismiss();
            }
        });

    }

    /**
     * 赚钱技巧
     */
    public void showEarnPrompt(String articleId,
                               String title, String imgUrl) {
        TextView tvDesc = v.findViewById(R.id.tv_share);
        LinearLayout iv_close = v.findViewById(R.id.iv_close);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(true);
        tvDesc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                NewsShare.showShareDialog(fragmentManager, activity, articleId, title, imgUrl);
            }
        });
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 赚钱技巧
     */
    public void showEarnPrompt() {
        TextView tvDesc = v.findViewById(R.id.tv_share);
        ImageView iv_close = v.findViewById(R.id.iv_close);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(true);
        tvDesc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 赚钱技巧
     */
    public void showEarnPromptOnly() {
        TextView tvDesc = v.findViewById(R.id.tv_share);
        LinearLayout iv_close = v.findViewById(R.id.iv_close);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(true);
        tvDesc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 签到接口
     */
    public void showQD() {
        ImageView tvDesc = v.findViewById(R.id.iv_close);//关闭
        RecyclerView recyclerView = v.findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(activity);
        newsAdapter = new QDNewsAdapter(activity, qdList);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(newsAdapter);
        newsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                String content = (Html.fromHtml(qdList.get(position).getContent())).subSequence(0, 50).toString();
                String url = qdList.get(position).getContentUrl();
                String imgUrl = qdList.get(position).getUrl();
                String title = qdList.get(position).getTitle();
                String articleReadId = qdList.get(position).getArticleId();
                String articleId = qdList.get(position).getRandomCode();
                String mDns = qdList.get(position).getmDns();
                Bundle bundle = new Bundle();
//                bundle.putString("url", url);
                bundle.putString("imgUrl", imgUrl);
                bundle.putString("articleId", articleId);
                bundle.putString("title", title);
                bundle.putString("articleReadId", articleReadId);
                NewsWebDetailActivity.forward(activity, bundle);
            }
        });
        getArticle();

        TextView tv_share = v.findViewById(R.id.tv_share);//换一批
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(true);
        tvDesc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //更换一批数据
                getArticle();
            }
        });

    }

    //获取签到列表
    private void getArticle() {
        Task.getApiService().toQD().enqueue(new MyCallback<NewsBaseEntity>(activity) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    assert response.body() != null;
                    String jsonStr = JSONObject.toJSONString(response.body().getData());
                    if (("1").equals(response.body().getCode())) {
                        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                        //表示下拉刷新
                        qdList.clear();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            NewsEntity newsEntity = new NewsEntity();
                            newsEntity.setMoney(jsonArray.getJSONObject(i).getInteger("incomeNum") + "");
                            newsEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            newsEntity.setUrl(jsonArray.getJSONObject(i).getString("image"));
                            newsEntity.setArticleId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            newsEntity.setmDns(jsonArray.getJSONObject(i).getString("remark"));
                            newsEntity.setRandomCode(jsonArray.getJSONObject(i).getString("randomCode"));
                            newsEntity.setPrice(jsonArray.getJSONObject(i).getInteger("price")+"");
                            qdList.add(newsEntity);
                        }
                        newsAdapter.notifyDataSetChanged();

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * 展示未打开的红包窗口
     */
    public void showRedPacket_unOpen() {
        ImageView tvDesc = v.findViewById(R.id.iv_close);//关闭窗口
        ImageView iv_open = v.findViewById(R.id.iv_open);//打开红包

        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        tvDesc.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        iv_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                v = (LayoutInflater.from(activity)).inflate(R.layout.item_redpacket_2, null);
                showRedPacketOpen();
                changeRedState();
            }
        });
    }

    //修改红包参数
    private void changeRedState() {
        int userId = Integer.parseInt(SPUtils.get(App.getContext(), "userId", "0") + "");
        Task.getApiService().getRedBag(userId).enqueue(new MyCallback<NewsBaseEntity>(activity) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                if ("1".equals(response.body().getCode()))
                    SPUtils.put(App.getContext(), "redBag", "1");
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * 展示打开状态的红包窗口
     */
    private void showRedPacketOpen() {
        ImageView tvDesc = v.findViewById(R.id.iv_close);//关闭窗口
        TextView tv_money = v.findViewById(R.id.tv_money);//金额
        TextView tv_withDrawNow = v.findViewById(R.id.tv_withDrawNow);//赚取更多金额
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        tv_withDrawNow.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    //加载动画
    public Dialog showLoad(String str) {
        ImageView iv_load = v.findViewById(R.id.iv_load);//
        TextView tv_pt = v.findViewById(R.id.tv_pt);
        tv_pt.setText(str);
        Glide.with(activity).load(R.drawable.refresh_juhua)
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(iv_load);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        return dialog;
    }


    //加载收益动画
    public Dialog showEarn(int x, int y) {
        try {
            dialog = builder.create();
            MyHandler handler = new MyHandler();
            ImageView iv_load = v.findViewById(R.id.iv_load);//
            Glide.with(activity)
                    .load(R.drawable.red)
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .listener(new RequestListener<Integer, GlideDrawable>() {

                        @Override
                        public boolean onException(Exception arg0, Integer arg1,
                                                   Target<GlideDrawable> arg2, boolean arg3) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource,
                                                       Integer model, Target<GlideDrawable> target,
                                                       boolean isFromMemoryCache, boolean isFirstResource) {
                            int duration = 0;
                            // 计算动画时长
                            GifDrawable drawable = (GifDrawable) resource;
                            GifDecoder decoder = drawable.getDecoder();
                            for (int i = 0; i < drawable.getFrameCount(); i++) {
                                duration += decoder.getDelay(i);
                            }
                            //发送延时消息，通知动画结束
                            handler.sendEmptyMessageDelayed(10,
                                    duration);
                            return false;
                        }
                    }) //仅仅加载一次gif动画
                    .into(new GlideDrawableImageViewTarget(iv_load, 1));
            Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
            dialog.show();
            //此处设置位置窗体大小
            dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
            dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
            dialog.setCancelable(false);
//            MyMediaManager.getInstance().playAudio(R.raw.earn);
        } catch (Exception e) {
            return dialog;
        }
        return dialog;
    }

    //静态内部类handler，防止内存泄漏
    private static class MyHandler extends Handler {


        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 10) {
                //平移动画
                dialog.dismiss();
            }

        }
    }

    /**
     * 动画平移
     *
     * @param v
     */
    private void Translate(View v, int x, int y) {
        /*
         * TranslateAnimation translateAni = new TranslateAnimation(fromXType,
         * fromXValue, toXType, toXValue, fromYType, fromYValue, toYType,
         * toYValue);
         */
        //参数1～2：x轴的开始位置
        //参数3～4：y轴的开始位置
        //参数5～6：x轴的结束位置
        //参数7～8：x轴的结束位置
        TranslateAnimation translateAni = new TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT,
                x, Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, y);

        //设置动画执行的时间，单位是毫秒
        translateAni.setDuration(10000);

        // 设置动画重复次数
        // -1或者Animation.INFINITE表示无限重复，正数表示重复次数，0表示不重复只播放一次
        translateAni.setRepeatCount(0);

        // 设置动画模式（Animation.REVERSE设置循环反转播放动画,Animation.RESTART每次都从头开始）
        translateAni.setRepeatMode(Animation.ABSOLUTE);

        // 启动动画
        v.startAnimation(translateAni);
        MyHandler handler = new MyHandler();
        handler.sendEmptyMessageDelayed(1,
                10000);
    }

    /**
     * @param title 标题 退出应用
     *              简单提示框  格式：内容、取消、确定
     */
    public void showQuitPrompt(String title) {
        TextView content = v.findViewById(R.id.prompt_content);
        content.setText(title);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (NewsForwardAnimation.instance != null) {
                    NewsForwardAnimation.instance = null;
                }
                activity.finish();
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }


    /**
     * 体现提交申请后弹框
     */
    @SuppressLint("SetTextI18n")
    public void showWithDrawPrompt(String msg) {

        TextView tvDesc = v.findViewById(R.id.tv_content);//描述文本
        tvDesc.setText(msg);

        LinearLayout iv_close = v.findViewById(R.id.iv_close);//关闭弹框

        TextView tv_service = v.findViewById(R.id.tv_service);//客服微信

        tv_service.setText("客服微信：" + AppConfig.getInstance(App.getContext()).get("wechat"));
        TextView tv_confirm = v.findViewById(R.id.tv_confirm);//点击确定按钮


        TextView tv_copy = v.findViewById(R.id.tv_copy);//复制微信


        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                activity.finish();
            }
        });
        tv_copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                CopyUtils.copyText(activity, AppConfig.getInstance(App.getContext()).get("wechat"));
//                getPermission();
                openWX();
            }
        });

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    //打开微信
    private void openWX() {
        if (CheckApkExist.checkApkExist(activity, "com.tencent.mm")) {
            Intent intent = new Intent();
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            activity.startActivity(intent);
        } else {
            NewsToastUtils.showToast(activity, "未安装手微信或安装的版本不支持！");
        }
    }

    /**
     * 体现提交申请后弹框
     */
    @SuppressLint("SetTextI18n")
    public void showCheckWithDrawPrompt(String msg) {

        TextView tvDesc = v.findViewById(R.id.tv_content);//描述文本
        tvDesc.setText(msg);

        LinearLayout iv_close = v.findViewById(R.id.iv_close);//关闭弹框

        TextView tv_service = v.findViewById(R.id.tv_service);//客服微信

        tv_service.setText("客服微信：" + AppConfig.getInstance(App.getContext()).get("wechat"));
        TextView tv_confirm = v.findViewById(R.id.tv_confirm);//点击确定按钮


        TextView tv_copy = v.findViewById(R.id.tv_copy);//复制微信


        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tv_copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                CopyUtils.copyText(activity, AppConfig.getInstance(App.getContext()).get("wechat"));
//                getPermission();
                openWX();
            }
        });

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 体现提交申请后弹框
     */
    @SuppressLint("SetTextI18n")
    public void showPromptNotice(List<NewsMainNoticeEntity> mainNoticeEntities) {
        final int[] position = {0};

        TextView tvDesc = v.findViewById(R.id.tv_title);//标题
        tvDesc.setText(mainNoticeEntities.get(position[0]).getTitle());
        TextView tvContent = v.findViewById(R.id.tv_content);//内容
        tvContent.setMovementMethod(ScrollingMovementMethod.getInstance());

        CharSequence charSequence = Html.fromHtml(mainNoticeEntities.get(position[0]).getContent());
        tvContent.setText(charSequence);
        TextView tv_copy = v.findViewById(R.id.tv_copy);//复制微信
        final Dialog dialog = builder.create();

        dialog.show();
        //此处设置位置窗体大小
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        tv_copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                position[0]++;
                Log.e("position", "onClick: " + position[0]);
                if (position[0] == mainNoticeEntities.size()) {
                    dialog.dismiss();
                } else {
                    tvDesc.setText((mainNoticeEntities.get(position[0]).getTitle()));
                    tvContent.setText(Html.fromHtml(mainNoticeEntities.get(position[0]).getContent()));
                }
//                if (mainNoticeEntities.get(position[0]).getPosition() == 1) {
//                    dialog.dismiss();
//                }

            }
        });
    }


    /**
     * 清除缓存
     *
     * @param title 标题
     *              简单提示框  格式：内容、取消、确定
     */

    public void clearMemory(String title) {
        TextView content = v.findViewById(R.id.prompt_content);
        content.setText(title);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Map<String, ?> map = SPUtils.getAll(activity);
                String privacyUrl = AppConfig.getInstance(App.getContext()).get("privacyUrl");
                String downLoadUrl = AppConfig.getInstance(App.getContext()).get("downLoadUrl");
                String strategyUrl = AppConfig.getInstance(App.getContext()).get("strategyUrl");
                String userUrl = AppConfig.getInstance(App.getContext()).get("userUrl");
                String newUrl = AppConfig.getInstance(App.getContext()).get("newUrl");
                String shareQQUrl = AppConfig.getInstance(App.getContext()).get("shareQQUrl");
                String shareUrl = AppConfig.getInstance(App.getContext()).get("shareUrl");
                String signUrl = AppConfig.getInstance(App.getContext()).get("signUrl");
                String articleUrl = AppConfig.getInstance(App.getContext()).get("articleUrl");
                String problemUrl = AppConfig.getInstance(App.getContext()).get("problemUrl");
                String redBagUrl = AppConfig.getInstance(App.getContext()).get("redBagUrl");
                String qq = AppConfig.getInstance(App.getContext()).get("qq");
                String iosGroupKeyUin = AppConfig.getInstance(App.getContext()).get("iosGroupKeyUin");
                String iosGroupKey = AppConfig.getInstance(App.getContext()).get("iosGroupKey");
                String wechat = AppConfig.getInstance(App.getContext()).get("wechat");
                String qqGroup = AppConfig.getInstance(App.getContext()).get("qqGroup");
                String groupKey = AppConfig.getInstance(App.getContext()).get("groupKey");
                String wxNumber = AppConfig.getInstance(App.getContext()).get("wxNumber");
                String articleUploadUrl = AppConfig.getInstance(App.getContext()).get("articleUploadUrl");
                String QQBrowserTip = AppConfig.getInstance(App.getContext()).get("QQBrowserTip");
                String WXLINETIP = AppConfig.getInstance(App.getContext()).get("WXLINETIP");
                String transfer_articleShareUrl = AppConfig.getInstance(App.getContext()).get("transfer_articleShareUrl");
                String pacg_appid=AppConfig.getInstance(App.getContext()).get("pacg_appid");
                DataCleanManager.clearAllCache(App.getContext());//清除缓存
                /*删除完之后 进行保存sharePreferences */
                for (int i = 0; i < map.size(); i++) {
                    Set<? extends Map.Entry<String, ?>> set = map.entrySet();
                    for (Map.Entry<String, ?> entry : set) {
                        SPUtils.put(activity, entry.getKey(), entry.getValue());
                    }
                }
                //还得保存所有的配置信息
                AppConfig.getInstance(App.getContext()).set("privacyUrl", privacyUrl);
                AppConfig.getInstance(App.getContext()).set("downLoadUrl", downLoadUrl);
                AppConfig.getInstance(App.getContext()).set("strategyUrl", strategyUrl);
                AppConfig.getInstance(App.getContext()).set("userUrl", userUrl);
                AppConfig.getInstance(App.getContext()).set("newUrl", newUrl);
                AppConfig.getInstance(App.getContext()).set("shareQQUrl", shareQQUrl);
                AppConfig.getInstance(App.getContext()).set("shareUrl", shareUrl);
                AppConfig.getInstance(App.getContext()).set("signUrl", signUrl);
                AppConfig.getInstance(App.getContext()).set("articleUrl", articleUrl);
                AppConfig.getInstance(App.getContext()).set("problemUrl", problemUrl);
                AppConfig.getInstance(App.getContext()).set("redBagUrl", redBagUrl);
                AppConfig.getInstance(App.getContext()).set("qq", qq);
                AppConfig.getInstance(App.getContext()).set("iosGroupKeyUin", iosGroupKeyUin);
                AppConfig.getInstance(App.getContext()).set("iosGroupKey", iosGroupKey);
                AppConfig.getInstance(App.getContext()).set("wechat", wechat);
                AppConfig.getInstance(App.getContext()).set("qqGroup", qqGroup);
                AppConfig.getInstance(App.getContext()).set("groupKey", groupKey);
                AppConfig.getInstance(App.getContext()).set("wxNumber", wxNumber);
                AppConfig.getInstance(App.getContext()).set("articleUploadUrl", articleUploadUrl);


                AppConfig.getInstance(App.getContext()).set("QQBrowserTip", QQBrowserTip);
                AppConfig.getInstance(App.getContext()).set("WXLINETIP", WXLINETIP);
                AppConfig.getInstance(App.getContext()).set("transfer_articleShareUrl", transfer_articleShareUrl);


                AppConfig.getInstance(App.getContext()).set("pacg_appid", pacg_appid);
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

    /**
     * @param title 标题 退出应用
     *              简单提示框  格式：内容、取消、确定
     */
    public void showSharePrompt(String title) {
        TextView content = v.findViewById(R.id.prompt_content);
        content.setText(title);
        TextView btn_sure = v.findViewById(R.id.userConfirm);
        TextView btn_cancel = v.findViewById(R.id.userCancel);
        final Dialog dialog = builder.create();
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(R.color.transparent);
        dialog.show();
        //此处设置位置窗体大小
        dialog.getWindow().setLayout(dip2px(activity, 280), LinearLayout.LayoutParams.WRAP_CONTENT);
        Objects.requireNonNull(dialog.getWindow()).setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
        dialog.setCancelable(false);
        btn_sure.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                openWX();
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
    }

}
